package bqds

import (
	"context"
	"database/sql"
	"encoding/json"
	"fmt"

	// redis "github.com/redis/go-redis/v9"

	"github.com/redis/go-redis/v9"
	"github.com/sirupsen/logrus"

	_ "github.com/taosdata/driver-go/v3/taosSql"
	// _ "github.com/taosdata/driver-go/v3/taosWS"

	ctpredis "gitee.com/boxigg/ctpredis"

	bqgo "gitee.com/boxigg/bqgo"
)

var (
	Rdb    *ctpredis.TdRedis
	RdbCtx context.Context

	taosurl = fmt.Sprintf("%s:%s@/tcp(%s:%d)/%s?interpolateParams=true", "vnpy", "steward1!", "127.0.0.1", 6030, "ctp")
	taosws  = fmt.Sprintf("%s:%s@ws(%s:%d)/%s", "root", "steward1!", "192.168.10.5", 6030, "vnpy")
)

type BqTaosDB struct {
	Rdb    *ctpredis.TdRedis
	user   string
	pwd    string
	ip     string
	port   int
	dbname string

	rip, rpwd string
	rport     int
	db        *sql.DB
}

// create BqTaosDB
// user,pwd, ip, dbname, port belont ot taosdb
// rip, rpwd, rport belong to ctpredis.TdRedis
// return BqTaosDB
func NewBqTaosDB(user, pwd, ip, dbname, rip, rpwd string, port, rport int) (db *BqTaosDB, err error) {

	rdb, err := ctpredis.NewTdRedis(rip, rpwd, rport)

	dns := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s", user, pwd, ip, port, dbname)
	tdb, err := sql.Open("taosSql", dns)
	db = &BqTaosDB{
		Rdb:    rdb,
		user:   user,
		pwd:    pwd,
		ip:     ip,
		port:   port,
		dbname: dbname,
		rip:    rip,
		rpwd:   rpwd,
		rport:  rport,
		db:     tdb,
	}
	if err != nil {
		panic(err)
		// return nil,err
	}
	return
}
func (db *BqTaosDB) InitTaosDB() {
	rdb := db.Rdb

	iids := rdb.GetMainIID()
	fmt.Print(iids)
}

// 通过订阅rdb将收到的数据保存到 taosdb tdb中
func ReceiveTickFromRedis(rdb *redis.Client) {

	psub := rdb.PSubscribe(RdbCtx, "Tick.*")
	ch := psub.Channel()
	go func() {
		defer psub.Close()
		for {
			for msg := range ch {
				// pattern:=msg.Pattern
				// channel := msg.Channel
				payload := msg.Payload
				// fmt.Println(channel)
				if payload != "" {
					go save2taosdb(payload)
				}
			}
		}
	}()
}

func save2taosdb(data string) {
	var tick bqgo.Tick
	if err := json.Unmarshal([]byte(data), &tick); err != nil {
		logrus.Error("解析tick错误:", data, " ", err)

	}
	fmt.Println(data)
}
func main() {

	// Rdb, RdbCtx = NewRedis("192.168.10.5", "steward1!", 6379, 0)
	// db,err:=sql.Open("taosSql",taosurl)
	fmt.Println(taosws)
	db, err := NewBqTaosDB("ctp", "steward1!", "192.168.10.5", "vnpy", "192.168.10.5", "steward1!", 6030, 6379)
	if err != nil {
		fmt.Println(err)
	}
	defer db.db.Close()
	db.db.Exec("show users;")
	// 测试连接

	fmt.Println("连接成功")
	go db.InitTaosDB()
	go ReceiveTickFromRedis(Rdb)
	// for {	}
}
